package org.goj.user.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.goj.common.entity.user.Team;
import org.goj.common.entity.user.TeamData;
import org.goj.common.entity.user.TeamUser;
import org.goj.user.mapper.TeamDataMapper;
import org.goj.user.mapper.TeamMapper;
import org.goj.user.mapper.TeamUserMapper;
import org.goj.user.service.TeamService;
import org.goj.user.service.TeamUserService;
import org.goj.user.vo.TeamAdminVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 团队表 服务实现类
 * </p>
 *
 * @author CK
 * @since 2021-05-05
 */
@Service
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService {

    @Resource
    private TeamMapper teamMapper;

    @Resource
    private TeamUserMapper teamUserMapper;

    @Resource
    private TeamDataMapper teamDataMapper;

    @Resource
    private TeamUserService teamUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertTeam(Integer userId, String title, String description, Integer status, Integer privilege, Integer teamId, String emails, String url) {
        Team team = new Team();
        if (teamId != -1) {
            team.setTeamId(teamId);
        }
        team.setUserId(userId).setTitle(title).setDescription(description).setStatus(status).setPrivilege(privilege).setSrc(url);
        if (teamId == -1) {
            int flag = teamMapper.insertTeam(team);
            Assert.isTrue(flag == 1, "添加团队失败");
        } else {
            boolean flag = super.updateById(team);
            Assert.isTrue(flag, "更新团队失败");
        }

        if (privilege == 1 && StrUtil.isNotBlank(emails)) {
            List<TeamUser> teamUsers = Arrays.stream(emails.split("\n")).map(t -> {
                TeamUser teamUser = new TeamUser();
                teamUser.setTeamId(team.getTeamId());
                teamUser.setEmail(t);
                return teamUser;
            }).collect(Collectors.toList());
            try {
                int teamNum = teamUserMapper.insertTeamBatch(teamUsers);
                Assert.isTrue(teamNum > 0, "添加用户失败");
            } catch (Exception e) {
                e.printStackTrace();
                Assert.isTrue(false, "添加用户失败");
            }
        }
    }

    @Override
    public Page<Team> teamListAdmin(Integer current, Integer size, String name) {
        Page<Team> page = new Page<>(current, size);
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(name), "team.title", name).or()
                .like(StrUtil.isNotBlank(name), "team.description", name)
                .orderByDesc("team_id");
        return teamMapper.teamListAdmin(page, queryWrapper);
    }

    @Override
    public TeamAdminVO teamByIdAdmin(Integer teamId) {
        Team team = teamMapper.selectById(teamId);
        TeamAdminVO teamAdminVO = new TeamAdminVO();
        BeanUtils.copyProperties(team, teamAdminVO);
        if (team.getPrivilege() == 1) {
            QueryWrapper<TeamUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("team_id", teamId);
            teamAdminVO.setEmails(
                    teamUserService.list(queryWrapper).stream().map(TeamUser::getEmail)
                            .filter(StrUtil::isNotBlank).collect(Collectors.joining("\n"))
            );
        }
        return teamAdminVO;
    }

    @Override
    public Page<Team> listTeam(Page<Team> page) {
        return teamMapper.listTeam(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeTeam(Integer teamId) {
        boolean b = super.removeById(teamId);
        Assert.isTrue(b, "删除团队失败");
        QueryWrapper<TeamData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("team_id", teamId);
        teamDataMapper.delete(queryWrapper);
        QueryWrapper<TeamUser> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("team_id", teamId);
        teamUserMapper.delete(queryWrapper1);
    }
}
